package com.ztl.usercenter02.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ztl.usercenter02.common.ErrorCode;
import com.ztl.usercenter02.exception.BusinessException;
import com.ztl.usercenter02.model.domain.User;
import com.ztl.usercenter02.service.UserService;
import com.ztl.usercenter02.mapper.UserMapper;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.regex.Pattern;

import static com.ztl.usercenter02.constant.UserConstant.USER_LOGIN_STATE;

/**
 * @author --
 * @description 针对表【user(用户表)】的数据库操作Service实现
 * @createDate 2024-04-11 15:36:34
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {
    /**
     * 盐值，用来混淆密码的
     */
    private static final String SALT = "ztl";



    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {

        //校验用户账户，密码，确认密码
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        //账户不小于4位
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账户过短");
        }
        //密码不小于8位
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码过短");
        }
        //两次密码要相同
        if(!userPassword.equals(checkPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        }
        //账户不能相同
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("userAccount", userAccount);
        long count = this.count(userQueryWrapper);
        if (count > 0) {
            return -1;
        }
        //账户不能包含特殊字符
        String REGEX = "^[a-zA-Z0-9_]+$";
        Pattern pattern = Pattern.compile(REGEX);
        boolean isMatch = pattern.matcher(userAccount).matches();
        if (!isMatch) {
            return -1;
        }
        //加密

        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        //插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        boolean result = this.save(user);
        if (!result) {
            return -1;
        }
        return user.getId();
    }

    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        //校验用户账户，密码，确认密码
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            return null;
        }
        //账户不小于4位
        if (userAccount.length() < 4) {
            return null;
        }
        //密码不小于8位
        if (userPassword.length() < 8 ) {
            return null;
        }

        //账户不能包含特殊字符
        String REGEX = "^[a-zA-Z0-9_]+$";
        Pattern pattern = Pattern.compile(REGEX);
        boolean isMatch = pattern.matcher(userAccount).matches();
        if (!isMatch) {
            return null;
        }
        //加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        //去数据库确认账户和密码是否匹配
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("UserPassword", encryptPassword);
        User user = this.getOne(queryWrapper);
        //用户为空
        if (user == null) {
            log.info("user login failed，userAccount not matched userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
        }
        //用户脱敏
        User safetyUser = saftyUser(user);
        //记录用户的登录态
        request.getSession().setAttribute(USER_LOGIN_STATE, safetyUser);

        return safetyUser;
    }

    @Override
    public User saftyUser(User user){
        if (user == null) {
            return null;
        }
        User safetyUser = new User();
        safetyUser.setId(user.getId());
        safetyUser.setUsername(user.getUsername());
        safetyUser.setUserAccount(user.getUserAccount());
        safetyUser.setAvatarUrl(user.getAvatarUrl());
        safetyUser.setGender(user.getGender());
        safetyUser.setPhone(user.getPhone());
        safetyUser.setEmail(user.getEmail());
        safetyUser.setUserRole(user.getUserRole());
        safetyUser.setUserStatus(user.getUserStatus());
        safetyUser.setCreateTime(user.getCreateTime());
        return safetyUser;
    }

    @Override
    public int userLoginOut(HttpServletRequest request) {
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 1;
    }
}




